// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const config = require("../../config")
const tool = require("../../utils/tool")
import * as echarts from '../../components/ec-canvas/echarts'

let chartData = undefined

Page({
  data: {
    currentPageId: 0,
    statusBarHeight: 0,
    contentHeight: 0,
    title: '',
    loginedUserInfo: undefined,
    showAppPage: false,
    loginAccount: '',
    loginPassword: '',
    loginWarningText: '',
    appName: '巡查e速办',
    currentSubPageId: 0,
    openId: '',
    registerPhoneNumber: '',
    registerVCode: '',
    registerName: '',
    registerId: '',
    registerPassword: '',
    registerRPassword: '',
    registerGetVCodeShowText: '获取验证码',
    subPageScrollTop: 0,
    subPageScrollStatus: 'up',
    complaintData: {},
    serverDownloadImageURL: '',
    showDCL: true,
    showDPJ: true,
    bgStatistics: undefined,
    showChart: false,
    homePageTopBarTop: 0,
    homePageTopBarSelected: -1,
    retrieveGetVCodeShowText: '获取验证码',
    userData: undefined,
    loginShowRegbutton: false,
    tj_xc_sf: '全部',
    tj_xc_xq: '全部',
    tj_xc_lx: '全部',
    tj_xc_dx: 'd7',
    tj_xc_dxName: '近7天',
    ec: {
      onInit: (canvas, width, height, dpr) => {
        let chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(chart);

        let colors1 = ['rgb(128, 255, 165)', 'rgb(0, 221, 255)', 'rgb(55, 162, 255)', 'rgb(255, 0, 135)', 'rgb(255, 191, 0)']
        let colors2 = ['rgb(1, 191, 236)', 'rgb(77, 119, 255)', 'rgb(116, 21, 219)', 'rgb(135, 0, 157)', 'rgb(224, 62, 76)']

        let ops = []
        let opsColors = ['#1fadff', '#00c03d', '#808080', '#FF0087', '#FFBF00']
        for (let i = 0; i < chartData.titles.length; i++) {
          ops.push({
            name: chartData.titles[i],
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            areaStyle: {
              opacity: 0.8,
              color: opsColors[i % 5]
            },
            emphasis: {
              focus: 'series'
            },
            data: chartData.data[chartData.titles[i]]
          })
        }

        var option = {
          color: ['#1fadff', '#00c03d', '#808080', '#FF0087', '#FFBF00'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          legend: {
            data: chartData.titles
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [{
            type: 'category',
            boundaryGap: false,
            data: chartData.ss
          }],
          yAxis: [{
            type: 'value'
          }],
          series: ops
        };

        chart.setOption(option);
        return chart;
      }
    },
    loadingLastTime: 0,
    homePageLoading: false,
    showStartPage: 0,
    shComViewType: '简略',
    canRefreshHomeData: true,
    functionPageOpacity: 0,
    homePageManagePageId: 0,
    homePageManagePageSelectLineLeft: '17px',
    homePageManagePageSearchUserType: '巡查人',
    homePageManagePageInput: '',
    homePageManagePageShowSXPage: false,
    homePageManagePageDateStart: false,
    homePageManagePageDateEnd: false,
    homePageManagePageSF: '不限制',
    homePageManagePageLX: '不限制',
    homePageManagePageXQ: '不限制',
    homePageManagePageSXPageTemp: undefined,
    comList: [],
    comListTotal: -1,
    homePageManagePagePage: 1,
    homePageManagePageSize: 10,
    homePageManagePageCardType: '简略',
    homePageManagePageSearching: false,
    homePageManagePageRefreshing: false,
    homePageManagePageRefreshing2: false,
    homePageSHLoading: false,
    homePageSHPage: 2,
    homePageSHSize: 10,
  },

  

  async handleScanQRCode() {
    let account = this.data.loginedUserInfo.account
    wx.scanCode({
      async success(e) {
        e = e.result
        try {
          e = tool.decodeString(e)
        } catch (error) {
          wx.showModal({
            title: '提示',
            content: '不支持此二维码',
            showCancel: false
          })
          return
        }
        e = e.split('lcuefix')[1]
        try {
          e = JSON.parse(e)
        } catch (error) {
          wx.showModal({
            title: '提示',
            content: '不支持此二维码',
            showCancel: false
          })
          return
        }
        if (e.op == 'webLogin') {
          wx.showModal({
            title: '提示',
            content: '是否在PC端登录当前账号？',
            complete: async (res) => {
              if (res.cancel) {

              }

              if (res.confirm) {
                let re = await tool.requestMethod('/user/qrcodeLogin/login', {
                  account: account,
                  string: e.string
                })
                if (re.status == 1) {
                  tool.showToast('登录成功')
                } else {
                  wx.showModal({
                    title: '提示',
                    content: re.content,
                    showCancel: false
                  })
                }
              }
            }
          })
          return
        }
        wx.showModal({
          title: '提示',
          content: '无操作',
          showCancel: false
        })
      }
    })
  },

  async homePageSHGetNext() {
    this.setData({
      homePageSHLoading: true
    })
    let re = await tool.requestMethod('/user/homeData/shGetNext', {
      account: this.data.loginedUserInfo.account,
      phoneNumber: this.data.loginedUserInfo.phoneNumber,
      page: this.data.homePageSHPage,
      size: this.data.homePageSHSize
    })
    this.setData({
      homePageSHLoading: false
    })
    this.setData({
      homePageSHPage: this.data.homePageSHPage + 1
    })
    if (re.status == 1) {
      let t = this.data.userData
      t.per.shData = [...t.per.shData, ...re.results.data]
      t.per.shDataTotal = re.results.total
      this.setData({
        userData: t,
      })
      console.log(t.per.shData)
    } else {
      tool.showToast(re.content)
    }

  },

  async homePageManagePageRefresh() {
    this.setData({
      homePageManagePagePage: 1,
      homePageManagePageRefreshing: true
    })
    await this.getComs(1)
    this.setData({
      homePageManagePageRefreshing: false
    })
  },

  async homePageManagePageGetNext() {
    this.setData({
      homePageManagePagePage: this.data.homePageManagePagePage + 1
    })
    this.setData({
      homePageManagePageSearching: true
    })
    await this.getComs()
    this.setData({
      homePageManagePageSearching: false
    })
  },

  homePageManagePageCardTypeChange() {
    wx.showActionSheet({
      itemList: ['正常', '简略'],
      success: (e) => {
        this.setData({
          homePageManagePageCardType: ['正常', '简略'][e.tapIndex]
        })
      }
    })

  },

  async homePageManageSearchComs() {
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    this.setData({
      homePageManagePagePage: 1,
      homePageManagePageShowSXPage: false
    })
    await this.getComs(true)
    wx.hideLoading()
  },

  async getComs(clear = false) {
    this.setData({
      homePageManagePageRefreshing2: true,
    })
    let re4 = await tool.requestMethod("/com/get", {
      type: 'admin',
      tsSearchFormStatus: this.data.homePageManagePageId == 0 ? '不限制' : (this.data.homePageManagePageId == 1 ? '待处理' : (this.data.homePageManagePageId == 2 ? '待评价' : '已完成')),
      tsSearchFormInput: this.data.homePageManagePageInput,
      tsSearchFormXQ: this.data.homePageManagePageXQ,
      tsSearchFormLX: this.data.homePageManagePageLX,
      tsSearchFormTSStart: this.data.homePageManagePageDateStart == false ? '不限制' : '限制',
      tsSearchFormTSEnd: this.data.homePageManagePageDateEnd == false ? '不限制' : '限制',
      tsSearchFormTSStartDate: this.data.homePageManagePageDateStart,
      tsSearchFormTSEndDate: this.data.homePageManagePageDateEnd,
      tsSearchFormUserType: this.data.homePageManagePageSearchUserType,
      page: this.data.homePageManagePagePage,
      size: this.data.homePageManagePageSize
    })
    this.setData({
      homePageManagePageRefreshing2: false
    })
    if (re4.status == -2) {
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
    }
    if (clear) {
      this.setData({
        comListTotal: 0,
        comList: []
      })
    }
    let comListCopy1 = this.data.comList
    for (let i = 0; i < re4.results.data.length; i++) {
      comListCopy1.push(re4.results.data[i])
    }
    this.setData({
      comList: comListCopy1,
      comListTotal: re4.results.total
    })
  },

  homePageManagePageDimensionChange(e) {
    let config = {}
    config["homePageManagePage" + e.currentTarget.dataset.type] = this.data.userData.dimension[e.currentTarget.dataset.type == 'SF' ? '身份' : (e.currentTarget.dataset.type == 'LX' ? '类别' : '校区')][e.detail.value]
    this.setData(config)
  },

  homePageManagePageDateEndChange(e) {
    this.setData({
      homePageManagePageDateEnd: e.detail.value
    })
  },

  homePageManagePageDateEndDelete() {
    this.setData({
      homePageManagePageDateEnd: false
    })
  },

  homePageManagePageDateStartChange(e) {
    this.setData({
      homePageManagePageDateStart: e.detail.value
    })
  },

  homePageManagePageDateStartDelete() {
    this.setData({
      homePageManagePageDateStart: false
    })
  },

  homePageManagePageShowSXPage() {
    if (this.data.homePageManagePageSXPageTemp != undefined) {
      this.setData({
        homePageManagePageInput: this.data.homePageManagePageSXPageTemp.homePageManagePageInput,
        homePageManagePageDateStart: this.data.homePageManagePageSXPageTemp.homePageManagePageDateStart,
        homePageManagePageDateEnd: this.data.homePageManagePageSXPageTemp.homePageManagePageDateEnd,
        homePageManagePageSF: this.data.homePageManagePageSXPageTemp.homePageManagePageSF,
        homePageManagePageLX: this.data.homePageManagePageSXPageTemp.homePageManagePageLX,
        homePageManagePageXQ: this.data.homePageManagePageSXPageTemp.homePageManagePageXQ,
      })
    }
    this.setData({
      homePageManagePageShowSXPage: true,
      // homePageManagePageSXPageTemp:{
      //   homePageManagePageInput:this.data.homePageManagePageInput,
      //   homePageManagePageDateStart:this.data.homePageManagePageDateStart,
      //   homePageManagePageDateEnd:this.data.homePageManagePageDateEnd,
      // }
    })
  },

  homePageManagePageHideSXPage() {
    this.setData({
      homePageManagePageShowSXPage: false
    })
  },

  homePageManagePageSearchUserTypeShowModal() {
    wx.showModal({
      title: '提示',
      content: '此选项表示你在搜索框里输入的用户信息在巡查中扮演的角色',
      showCancel: 0
    })
  },

  homePageManagePageSearchInput(e) {
    this.setData({
      homePageManagePageInput: e.detail.value
    })
  },

  homePageManagePageSearchInputClear() {
    this.setData({
      homePageManagePageInput: ''
    })
  },

  changeHomePageManageSearchUserType(e) {
    e = e.detail.value
    this.setData({
      homePageManagePageSearchUserType: ['巡查人', '负责人', '审核人'][e]
    })
  },

  changeHomePageManagePage(e) {
    e = e.currentTarget.dataset.id
    this.setData({
      homePageManagePageId: e
    })
    switch (e) {
      case 0:
        this.setData({
          homePageManagePageSelectLineLeft: '17px'
        })
        break;
      case 1:
        this.setData({
          homePageManagePageSelectLineLeft: '17px + 3em'
        })
        break;
      case 2:
        this.setData({
          homePageManagePageSelectLineLeft: '17px + 7em'
        })
        break;
      case 3:
        this.setData({
          homePageManagePageSelectLineLeft: '17px + 11em'
        })
        break;
    }
    this.setData({
      homePageManagePagePage: 1
    })
    this.homePageManageSearchComs(1)
  },

  showBgLogPage() {
    wx.navigateTo({
      url: '/pages/logs/logs?data=' + JSON.stringify({
        loginedUserInfo: this.data.loginedUserInfo,
        statusBarHeight: this.data.statusBarHeight,
        contentHeight: this.data.contentHeight
      }),
    })
  },

  setCantRefreshHomeData() {
    this.setData({
      canRefreshHomeData: false
    })
  },

  setCanRefreshHomeData() {
    this.setData({
      canRefreshHomeData: true
    })
  },

  changeSHComViewType() {
    let types = ['正常', '简略']
    wx.showActionSheet({
      itemList: types,
      success: (e) => {
        this.setData({
          shComViewType: types[e.tapIndex]
        })
      }
    })
  },

  async tj_xc_change(e) {
    let config = {

    }
    config["tj_xc_" + e.currentTarget.dataset.type] = this.data.bgStatistics.dimensionType[e.currentTarget.dataset.type][parseInt(e.detail.value)]
    // console.log(e.detail.value)
    console.log(this.data.bgStatistics.dimensionType[e.currentTarget.dataset.type][parseInt(e.detail.value)].toString())
    this.setData(config)
    if (e.currentTarget.dataset.type == 'dx') {
      this.setData({
        tj_xc_dxName: '近' + this.data.bgStatistics.dimensionType[e.currentTarget.dataset.type][parseInt(e.detail.value)].toString().slice(1, this.data.bgStatistics.dimensionType[e.currentTarget.dataset.type][parseInt(e.detail.value)].toString().length) + '天'
      })
    }
    await this.getChartData()
    await this.prepareChartData(this.data.tj_xc_sf, this.data.tj_xc_xq, this.data.tj_xc_lx, this.data.tj_xc_dx)
  },
  async checkLoginShowRegButton() {
    let re = await tool.requestMethod("/setting/get", {
      keyName: 'zc'
    })
    if (re.status == 1) {
      re = re.results
      this.setData({
        loginShowRegbutton: re
      })
    }

  },
  showBgUserListPage() {
    wx.navigateTo({
      url: '/pages/userList/userList?data=' + JSON.stringify({
        statusBarHeight: this.data.statusBarHeight,
        contentHeight: this.data.contentHeight,
        loginedUserInfo: this.data.loginedUserInfo
      }),
    })
  },
  async homePageTopBarFunctionChange(e) {
    this.deviceVS()
    this.setData({
      homePageTopBarSelected: e.currentTarget.dataset.index,
      shComViewType: '简略'
    })
  },
  async prepareChartData(SF = '全部', XQ = '全部', LX = '全部', DX = 'd7') {
    this.setData({
      showChart: false
    })
    await tool.waitSeconds(0.001)
    chartData = tool.getChartData(this.data.bgStatistics, SF, XQ, LX, DX)
    this.setData({
      showChart: true,
      numData: chartData.numData
    })
  },
  async retrieve_buttonClick() {
    if (this.data.registerId.length == 0) {
      this.setData({
        loginWarningText: '学号/工号不能为空'
      })
      return
    }
    if (this.data.registerPhoneNumber.length != 11) {
      this.setData({
        loginWarningText: '电话号码格式有误'
      })
      return
    }
    let t = this.data.registerPhoneNumber.split('')
    for (let i = 0; i < t.length; i++) {
      t[i] = t[i].charCodeAt(0)
      if (t[i] >= 48 && t[1] <= 57) continue
      this.setData({
        loginWarningText: '电话号码格式有误'
      })
      return
    }
    if (this.data.registerVCode.length != 6) {
      this.setData({
        loginWarningText: '验证码格式有误'
      })
      return
    }
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    let re = await tool.requestMethod("/user/reSetPassword", {
      vcode: this.data.registerVCode,
      phoneNumber: this.data.registerPhoneNumber,
      account: this.data.registerId
    })
    wx.hideLoading()
    if (re.status == -2) {
      this.setData({
        loginWarningText: '后端服务异常'
      })
      return
    }
    if (re.status == 0) {
      this.setData({
        loginWarningText: re.content
      })
      return
    }
    wx.showModal({
      title: '提示',
      content: '密码已重置为 12345678',
      showCancel: false,
      complete: async (res) => {
        this.setData({
          currentPageId: -1
        })
        wx.showLoading({
          mask: true,
          title: '请稍候',
        })
        await tool.waitSeconds(1)
        this.setData({
          currentPageId: 0,
          title: '',
          loginWarningText: ''
        })
        wx.hideLoading()
      }
    })
  },
  async showRetrievePage() {
    this.setData({
      currentPageId: -1
    })
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    await tool.waitSeconds(2)
    wx.hideLoading()
    this.setData({
      currentPageId: 3,
      registerPhoneNumber: '',
      registerVCode: '',
      registerId: ''
    })
    this.refreshTitle()
  },
  async showFunctionPageClick() {
    this.deviceVS()
    this.changeSubPage1()
  },
  showBgComPageClick(e) {
    this.deviceVS()
    this.showBgComPage(e)
  },
  onReady() {

  },
  async onLoad() {

    //将未读通知打开通知中心设为true
    wx.setStorageSync('unreadOpenNotificationCenter', true)

    try {
      if (wx.getStorageSync('startup') == '' || wx.getStorageSync('startup') == null) {
        wx.setStorageSync('startup', '主页-最近')
      }
    } catch (error) {

    }


    if (wx.getStorageSync('clearCache') == '') {
      wx.setStorageSync('clearCache', '7')
    }
    tool.deleteLongTimeNotUseImg()

    if (wx.getStorageSync('themeSetting') == '') {
      wx.setStorageSync('themeSetting', 'auto')
      wx.setStorageSync('theme', wx.getSystemInfoSync().theme)
    } else {
      switch (wx.getStorageSync('themeSetting')) {
        case 'light':
          wx.setStorageSync('theme', 'light')
          break;
        case 'dark':
          wx.setStorageSync('theme', 'dark')
          break;
        case 'auto':
          wx.setStorageSync('theme', wx.getSystemInfoSync().theme)
          break;
      }
    }

    tool.setThemeColor(this)

    wx.setStorageSync('sysImagURLPrefix', config.serverURL + '/file/download/')
    this.setData({
      sysImagURLPrefix: wx.getStorageSync('sysImagURLPrefix')
    })
    this.setData({
      statusBarHeight: (wx.getSystemInfoSync().statusBarHeight + 50).toString() + 'px',
      contentHeight: (wx.getSystemInfoSync().windowHeight - (wx.getSystemInfoSync().statusBarHeight + 54)).toString() + 'px',
      bannerHeight: ((wx.getSystemInfoSync().windowWidth - 34) * 0.3899).toString() + 'px',
      serverDownloadImageURL: config.serverURL + "/file/download"
    })
    // wx.showLoading({ mask:true,
    //   title: '请稍候',
    // })
    await this.checkLoginShowRegButton()
    let code = await tool.getLoginCode()
    let re = await tool.requestMethod('/openId', {
      code: code
    })
    this.setData({
      openId: re.results
    })
    if (re.status == -2) {
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
      return
    }
    re = await tool.requestMethod('/autoLogin', {
      openId: re.results
    })
    if (re.status == -2) {
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
      return
    }
    if (re.status == 0) {
      this.setData({
        showAppPage: true
      })
    } else {
      re = re.results
      re.avatarText = re.name.slice(re.name.length - 2, re.name.length)
      this.setData({
        loginedUserInfo: re,
        currentPageId: 1,
      })
      if (re.type == 'admin') {

        await this.checkAdminPassword()
      }
      await this.getCom(this.data.loginedUserInfo.type, false)
      await this.getUserData()
      this.setData({
        showAppPage: true,
      })
    }
    this.hideStartPage()
    this.refreshTitle()
    wx.hideLoading()
    if (this.data.loginedUserInfo && this.data.loginedUserInfo.type == 'admin') {
      await this.getChartData()
      this.prepareChartData()
    }

    try {
      this.setData({
        currentSubPageId: 0
      })
      switch (wx.getStorageSync('startup')) {
        case '主页-最近':
          this.setData({
            homePageTopBarSelected: -1
          })
          break;
        case '主页-巡查':
          this.setData({
            homePageTopBarSelected: 0
          })
          break;
        case '主页-评价':
          this.setData({
            homePageTopBarSelected: 3
          })
          break;
        case '主页-处理':
          this.setData({
            homePageTopBarSelected: 1
          })
          if (this.data.userData.per.showCLButton == false) {
            this.setData({
              homePageTopBarSelected: -1
            })
            wx.setStorageSync('startup', '主页-最近')
          }
          break;
        case '主页-审核':
          this.setData({
            homePageTopBarSelected: 2
          })
          if (this.data.userData.per.showSHButton == false) {
            this.setData({
              homePageTopBarSelected: -1
            })
            wx.setStorageSync('startup', '主页-最近')
          }
          break;
        case '管理':
          this.setData({
            currentSubPageId: 2
          })
          this.getComs()
          if (this.data.userData.per.showGLButton == false) {
            this.setData({
              homePageTopBarSelected: -1
            })
            wx.setStorageSync('startup', '主页-最近')
          } else {
            this.setData({
              title: '管理'
            })
          }
          break;
      }
    } catch (error) {

    }
  },
  async hideStartPage() {
    await tool.waitSeconds(0.2)
    this.setData({
      showStartPage: 1
    })
    await tool.waitSeconds(0.3)
    this.setData({
      showStartPage: 2
    })
  },
  async download() {
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    wx.downloadFile({
      url: config.serverURL + '/export/file/1',
      success: function (res) {
        wx.hideLoading()
        const filePath = res.tempFilePath // 临时文件路径
        wx.openDocument({
          filePath: filePath,
          showMenu: true // 预览文件右上方的...
        })
      }
    })
  },
  async download2() {
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    wx.downloadFile({
      url: config.serverURL + '/export/file/2',
      success: function (res) {
        wx.hideLoading()
        const filePath = res.tempFilePath // 临时文件路径
        wx.openDocument({
          filePath: filePath,
          showMenu: true // 预览文件右上方的...
        })
      }
    })
  },
  async download3() {
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    wx.downloadFile({
      url: config.serverURL + '/export/file/3',
      success: function (res) {
        wx.hideLoading()
        const filePath = res.tempFilePath // 临时文件路径
        wx.openDocument({
          filePath: filePath,
          showMenu: true // 预览文件右上方的...
        })
      }
    })
  },
  async getUserData() {
    if (this.data.loginedUserInfo == undefined) return
    let re = await tool.requestMethod("/user/homeData", {
      account: this.data.loginedUserInfo.account
    })
    console.log(re)
    if (re.status == -2) {
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
    }
    let t = this.data.loginedUserInfo
    t.name = re.results.name
    t.avatarText = re.results.name.slice(re.results.name.length - 2, re.results.name.length)
    this.setData({
      userData: re.results,
      loginedUserInfo: t
    })

    //检查有无未读通知
    if (this.data.userData.notification.unread && wx.getStorageSync('unreadOpenNotificationCenter') && this.data.loginedUserInfo.type != 'admin') {
      tool.navigateTo(this, 'notification', {
        type: 'userList',
      })
      wx.setStorageSync('unreadOpenNotificationCenter', false)
    }
  },
  async checkAdminPassword() {
    return
    if (this.data.loginedUserInfo == undefined) return
    let re23 = await tool.requestMethod("/user/phoneNumber", {
      account: "admin"
    })
    if (re23.results == '') {
      this.setData({
        currentPageId: -2
      })
      wx.showModal({
        title: '提示',
        content: '请先绑定您的手机号',
        complete: async (res) => {
          if (res.cancel) {
            await tool.requestMethod("/exitLogin", {
              account: 'admin'
            })
            this.setData({
              currentPageId: 0,
              loginedUserInfo: ''
            })
            this.refreshTitle()
            wx.showModal({
              title: '提示',
              content: '需要绑定手机号才能继续使用，已退出登录',
              showCancel: false
            })
          }

          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/changePhoneNumber/changePhoneNumber?data=' + JSON.stringify({
                statusBarHeight: this.data.statusBarHeight,
                contentHeight: this.data.contentHeight,
                loginedUserInfo: this.data.loginedUserInfo
              }),
            })
          }
        }
      })
      return true
    } else {
      return false
    }
  },
  async retrieveGetVCodeClick() {
    if (this.data.retrieveGetVCodeShowText != '获取验证码') {
      return
    }
    if (this.data.registerId.length == 0) {
      this.setData({
        loginWarningText: '学号/工号不能为空'
      })
      return
    }
    if (this.data.registerPhoneNumber.length != 11) {
      this.setData({
        loginWarningText: '电话号码格式有误'
      })
      return
    }
    let t = this.data.registerPhoneNumber.split('')
    for (let i = 0; i < t.length; i++) {
      t[i] = t[i].charCodeAt(0)
      if (t[i] >= 48 && t[1] <= 57) continue
      this.setData({
        loginWarningText: '电话号码格式有误'
      })
      return
    }
    // if(this.data.register_VCodeInput.length!=6){
    //   this.setData({
    //     loginWarningText:'验证码格式有误'
    //   })
    //   return
    // }
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    let re = await tool.requestMethod("/user/reSetPasswordGetVCode", {
      account: this.data.registerId,
      phoneNumber: this.data.registerPhoneNumber
    })
    wx.hideLoading()
    if (re.status == -2) {
      this.setData({
        loginWarningText: '后端服务异常'
      })
      return
    }
    if (re.status == 0) {
      this.setData({
        loginWarningText: re.content
      })
      return
    }
    for (let i = 59; i > 0; i--) {
      this.setData({
        retrieveGetVCodeShowText: i.toString() + 's'
      })
      await tool.waitSeconds(1)
    }
    this.setData({
      registerGetVCodeShowText: '获取验证码'
    })
  },
  showDPJHideDCL() {
    this.setData({
      showDCL: false,
      showDPJ: true
    })
  },
  controlDCL() {
    if (this.data.showDCL) {
      this.setData({
        showDCL: false
      })
    } else {
      this.setData({
        showDCL: true
      })
    }
  },
  controlDPJ() {
    if (this.data.showDPJ) {
      this.setData({
        showDPJ: false
      })
    } else {
      this.setData({
        showDPJ: true
      })
    }
  },
  async makePhoneCall(e) {
    e = e.currentTarget.dataset.account
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    let re = await tool.requestMethod("/user/phoneNumber", {
      account: e
    })
    wx.hideLoading()
    if (re.status == -2) {
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
      return
    }
    if (re.results.length != 11) {
      wx.showModal({
        title: '提示',
        content: '当前帐号未设置电话号码',
        showCancel: false
      })
      return
    }
    wx.makePhoneCall({
      phoneNumber: re.results,
    })
  },
  async cb(item) {
    item = item.currentTarget.dataset.item
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    let re = await tool.requestMethod("/com/hasten", {
      id: item.id
    })
    wx.hideLoading()
    if (re.status == -2) {
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
      return
    }
    if (re.status == 0) {
      wx.showToast({
        title: re.content,
        icon: 'none'
      })
      return
    }
    wx.showToast({
      title: '催办成功',
      icon: 'none'
    })
  },
  showComDetail(id) {
    if (id.currentTarget != undefined) {
      id = id.currentTarget.dataset.id
    }
    wx.navigateTo({
      url: '/pages/comDetail/conDetail?data=' + JSON.stringify({
        id: id,
        statusBarHeight: this.data.statusBarHeight,
        contentHeight: this.data.contentHeight,
        loginedUserInfo: this.data.loginedUserInfo
      }),
    })
  },
  showComItemMenu(e) {
    e = e.currentTarget.dataset.item
    let menu = []
    if (e.account == this.data.loginedUserInfo.account) {
      if (e.account2 == '' && e.content3.length == 0) {
        menu = ['详情', '撤回']
      } else {
        menu = ['详情']
      }
    } else {
      menu = ['详情']
    }
    wx.showActionSheet({
      itemList: menu,
      success: async res => {
        res = res.tapIndex
        switch (res) {
          case 0:
            this.showComDetail(e.id)
            break;
          case 1:
            wx.showModal({
              title: '提示',
              content: '是否撤回此巡查？',
              complete: async (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {
                  wx.showLoading({
                    mask: true,
                    title: '请稍候',
                  })
                  let re = await tool.requestMethod("/com/withdraw", {
                    id: e.id
                  })
                  wx.hideLoading()
                  if (re.status == -2) {
                    wx.showModal({
                      title: '提示',
                      content: '后端服务异常',
                      showCancel: false
                    })
                    return
                  }
                  if (re.status == 0) {
                    wx.showModal({
                      title: '提示',
                      content: re.content,
                      showCancel: false
                    })
                    return
                  }
                  this.getUserData()
                }
              }
            })
            break
        }
      }
    })
  },
  showImageViewer(e) {
    for (let i = 0; i < e.currentTarget.dataset.arr.length; i++) {
      e.currentTarget.dataset.arr[i] = config.serverURL + '/file/download/' + e.currentTarget.dataset.arr[i]
    }
    console.log(e)
    wx.previewImage({
      urls: e.currentTarget.dataset.arr,
      current: config.serverURL + '/file/download/' + e.currentTarget.dataset.current
    })
  },
  async getCom(type = this.data.loginedUserInfo.type, showLoading = true) {
    if (showLoading) {
      wx.showLoading({
        mask: true,
        title: '请稍候',
      })
    }
    let re = await tool.requestMethod("/com/get", {
      type: type,
      account: this.data.loginedUserInfo.account
    })
    wx.hideLoading()
    if (re.status == -2) {
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
      return
    }
    this.setData({
      complaintData: re.results
    })
  },
  addCom_click() {
    wx.navigateTo({
      url: '/pages/addCom/addCom?data=' + JSON.stringify({
        statusBarHeight: this.data.statusBarHeight,
        contentHeight: this.data.contentHeight,
        loginedUserInfo: this.data.loginedUserInfo
      }),
    })
  },
  deviceVS() {
    wx.vibrateShort({
      type: 'light',
    })
  },
  subPageScroll(e) {
    e = e.detail.scrollTop
    if (e <= 1) {
      this.setData({
        homePageTopBarTop: 0
      })
      return
    }
    if (e > this.data.subPageScrollTop) {
      let c = this.data.subPageScrollTop - e
      if (this.data.homePageTopBarTop + c <= -80) {
        this.setData({
          homePageTopBarTop: -80
        })
      } else {
        this.setData({
          homePageTopBarTop: this.data.homePageTopBarTop + c
        })
      }
      this.setData({
        subPageScrollStatus: 'down',
        subPageScrollTop: e
      })
    } else {
      let c = this.data.subPageScrollTop - e
      if (this.data.homePageTopBarTop + c > 0) {
        this.setData({
          homePageTopBarTop: 0
        })
      } else {

        this.setData({
          homePageTopBarTop: this.data.homePageTopBarTop + c
        })
      }
      this.setData({
        subPageScrollStatus: 'up',
        subPageScrollTop: e
      })
    }
  },
  async registerGetVCodeClick() {
    if (this.data.registerGetVCodeShowText != '获取验证码') {
      return
    }
    this.setData({
      loginWarningText: ''
    })
    if (this.data.registerPhoneNumber.length != 11) {
      this.setData({
        loginWarningText: '电话号码格式有误'
      })
      return
    }
    let t = this.data.registerPhoneNumber.split('')
    for (let i = 0; i < t.length; i++) {
      t[i] = t[i].charCodeAt(0)
      if (t[i] >= 48 && t[i] <= 57) continue
      this.setData({
        loginWarningText: '电话号码格式有误'
      })
      return
    }
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    let re = await tool.requestMethod('/register/getVcode', {
      phoneNumber: this.data.registerPhoneNumber,
    })
    wx.hideLoading()
    if (re.status == -2) {
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
      return
    } else if (re.status == 0) {
      this.setData({
        loginWarningText: re.content
      })
      return
    } else {

    }
    for (let i = 59; i >= 1; i--) {
      this.setData({
        registerGetVCodeShowText: i.toString() + 's'
      })
      await tool.waitSeconds(1)
    }
    this.setData({
      registerGetVCodeShowText: '获取验证码'
    })
  },
  async register_buttonClick() {
    this.setData({
      loginWarningText: ''
    })
    if (this.data.registerPhoneNumber.length != 11) {
      this.setData({
        loginWarningText: '电话号码格式有误'
      })
      return
    }
    if (this.data.registerVCode.length != 6) {
      this.setData({
        loginWarningText: '验证码应为6位'
      })
      return
    }
    if (this.data.registerId == '') {
      this.setData({
        loginWarningText: '学号/工号不能为空'
      })
      return
    }
    if (this.data.registerName == '') {
      this.setData({
        loginWarningText: '用户名不能为空'
      })
      return
    }
    if (this.data.registerPassword == '') {
      this.setData({
        loginWarningText: '登录密码不能为空'
      })
      return
    }
    if (this.data.registerRPassword == '') {
      this.setData({
        loginWarningText: '请再次输入登录密码'
      })
      return
    }
    if (this.data.registerPassword.length < 8 || this.data.registerPassword.length > 16) {
      this.setData({
        loginWarningText: '登录密码应不短于8位、不长于16位'
      })
      return
    }
    if (this.data.registerPassword != this.data.registerRPassword) {
      this.setData({
        loginWarningText: '两次输入的登录密码不一致'
      })
      return
    }
    let t = this.data.registerPassword.split('')
    for (let i = 0; i < t.length; i++) {
      t[i] = t[i].charCodeAt(0)
      if (t[i] >= 48 && t[i] <= 57) continue
      if (t[i] >= 65 && t[i] <= 90) continue
      if (t[i] >= 97 && t[i] <= 122) continue
      this.setData({
        loginWarningText: '登录密码应由数字或大小写字母组成'
      })
      return
    }
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    let re = await tool.requestMethod("/register/add", {
      account: this.data.registerId,
      password: tool.sha256(this.data.registerPassword),
      vcode: this.data.registerVCode,
      name: this.data.registerName,
      phoneNumber: this.data.registerPhoneNumber
    })
    wx.hideLoading()
    if (re.status == -2) {
      wx.showModal({
        title: '提示',
        content: '后端服务异常',
        showCancel: false
      })
      return
    }
    if (re.status == 0) {
      this.setData({
        loginWarningText: re.content
      })
      return
    }
    wx.showModal({
      title: '提示',
      content: re.content,
      showCancel: false,
      complete: async (res) => {
        this.setData({
          currentPageId: -1
        })
        wx.showLoading({
          mask: true,
          title: '请稍候',
        })
        this.setData({
          title: ''
        })
        await tool.waitSeconds(1)
        wx.hideLoading()
        this.setData({
          registerId: '',
          registerName: '',
          registerVCode: '',
          registerPhoneNumber: '',
          registerPassword: '',
          registerRPassword: '',
          loginWarningText: '',
          currentPageId: 0,
          title: ''
        })
      }
    })
  },
  register_phoneNumberInput(e) {
    this.setData({
      registerPhoneNumber: e.detail.value
    })
  },
  register_VCodeInput(e) {
    this.setData({
      registerVCode: e.detail.value
    })
  },
  register_idInput(e) {
    this.setData({
      registerId: e.detail.value
    })
  },
  register_nameInput(e) {
    this.setData({
      registerName: e.detail.value
    })
  },
  register_passwordInput(e) {
    this.setData({
      registerPassword: e.detail.value
    })
  },
  register_rPasswordInput(e) {
    this.setData({
      registerRPassword: e.detail.value
    })
  },
  async backToLoginPage() {
    this.setData({
      currentPageId: -1,
      loginWarningText: '',
    })
    this.refreshTitle()
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    await tool.waitSeconds(1)
    wx.hideLoading()
    this.setData({
      currentPageId: 0
    })
  },
  async showRegisterPage() {
    this.setData({
      currentPageId: -1,
      loginWarningText: ''
    })
    wx.showLoading({
      mask: true,
      title: '请稍候',
    })
    await tool.waitSeconds(2)
    wx.hideLoading()
    this.setData({
      currentPageId: 2,
      loginWarningText: '',
      register_phoneNumberInput: '',
      register_VCodeInput: '',
      register_idInput: '',
      register_nameInput: '',
      register_passwordInput: '',
      register_rPasswordInput: ''
    })
    this.refreshTitle()
  },
  showBgMyComPage() {
    this.showPage('/pages/bg/bg', '与我相关的巡查')
  },
  showBgNotificationMgrPage() {
    wx.navigateTo({
      url: '/pages/notification/notification?data=' + JSON.stringify({
        statusBarHeight: this.data.statusBarHeight,
        contentHeight: this.data.contentHeight,
        loginedUserInfo: this.data.loginedUserInfo,
        type: 'management'
      }),
    })
  },
  showBgNotificationUserListPage() {
    console.log(123)
    wx.navigateTo({
      url: '/pages/notification/notification?data=' + JSON.stringify({
        statusBarHeight: this.data.statusBarHeight,
        contentHeight: this.data.contentHeight,
        loginedUserInfo: this.data.loginedUserInfo,
        type: 'userList'
      }),
    })
  },
  showBgMyComPageWithType(e) {
    if (e.currentTarget.dataset.dsv) {
      this.deviceVS()
    }
    this.showPage('/pages/bg/bg', '与我相关的巡查', {
      type: e.currentTarget.dataset.type
    })
  },
  mpk(e) {
    tool.showComPhoneNumberList(this.data.statusBarHeight, this.data.contentHeight, this.data.loginedUserInfo, e.currentTarget.dataset.id)
  },
  showBgComPage(e = undefined) {
    if (e != undefined && Object.keys(e.currentTarget.dataset).length != 0) {
      this.showPage('/pages/bg/bg', '管理巡查', {
        account2: e.currentTarget.dataset.item.account,
        type: e.currentTarget.dataset.type
      })
    } else {
      this.showPage('/pages/bg/bg', '管理巡查')
    }

  },
  showBgNotificationPage() {
    this.showPage('/pages/bg/bg', '功能开关')
  },
  showBgUserPage() {
    this.showPage('/pages/bg/bg', '负责人和审核人管理')
  },
  showBgDimenPage() {
    this.showPage('/pages/bg/bg', '多维度管理设置')
  },
  showPage(url, mgType, data = undefined) {
    wx.navigateTo({
      url: url + '?data=' + JSON.stringify({
        statusBarHeight: this.data.statusBarHeight,
        contentHeight: this.data.contentHeight,
        mgType: mgType,
        loginedUserInfo: this.data.loginedUserInfo,
        account2: data == undefined ? undefined : data.account2,
        type: data == undefined ? undefined : data.type
      }),
    })
  },
  async refreshHomePageData() {
    this.setData({
      homePageLoading: true
    })
    await this.getUserData()
    this.setData({
      homePageLoading: false
    })
    if (this.data.loginedUserInfo.type == 'admin') {
      await this.getChartData()
      this.prepareChartData()
    }

    tool.showToast('刷新成功')
  },
  async changeSubPage0() {
    if (this.data.currentSubPageId == 0) {
      if (this.data.loadingLastTime != 0) {
        tool.showToast('请' + this.data.loadingLastTime.toString() + '秒后再刷新')
      } else {
        this.refreshHomePageData()
        for (let i = 10; i >= 0; i--) {
          this.setData({
            loadingLastTime: i
          })
          await tool.waitSeconds(1)
        }
      }
      return
    }
    this.setData({
      currentSubPageId: 0,
      homePageTopBarTop: 0
    })
    this.refreshTitle()
  },
  async changeSubPage1() {
    this.setData({
      currentSubPageId: 1
    })
    this.refreshTitle()
    await tool.waitSeconds(0.001)
    this.setData({
      functionPageOpacity: 1
    })
  },
  async changeSubPage2() {
    if (this.data.currentSubPageId == 2) {
      this.homePageManagePageRefresh()
    }
    this.setData({
      currentSubPageId: 2
    })
    this.refreshTitle()
    if (this.data.comListTotal == -1) {
      this.homePageManageSearchComs()
    }
  },
  refreshTitle() {
    this.setData({
      title: this.getTitle()
    })
  },
  showUserPage() {
    wx.navigateTo({
      url: '/pages/user/user?data=' + JSON.stringify({
        statusBarHeight: this.data.statusBarHeight,
        loginedUserInfo: this.data.loginedUserInfo,
        contentHeight: this.data.contentHeight
      }),
    })
  },
  login_accountInput(e) {
    this.setData({
      loginAccount: e.detail.value
    })
  },
  login_passwordInput(e) {
    this.setData({
      loginPassword: e.detail.value
    })
  },
  async login_buttonClick() { //点击登录按钮
    this.setData({
      loginWarningText: ''
    })
    if (this.data.loginAccount == '') {
      this.setData({
        loginWarningText: '请输入账号'
      })
      return
    }
    if (this.data.loginPassword == '') {
      this.setData({
        loginWarningText: '请输入密码'
      })
      return
    }
    wx.showLoading({
      mask: true,
      title: '正在登录',
    })
    let re = await tool.requestMethod('/login', {
      openId: this.data.openId,
      account: this.data.loginAccount,
      password: tool.sha256(this.data.loginPassword)
    })
    wx.hideLoading()
    if (re.status == -2) {
      this.setData({
        loginWarningText: '后端服务异常'
      })
      return
    }
    if (re.status == 0) {
      this.setData({
        loginWarningText: re.content
      })
      return
    }
    re.results.avatarText = re.results.name.slice(re.results.name.length - 2, re.results.name.length)
    this.setData({
      loginedUserInfo: re.results,
      showAppPage: -1,
    })
    await this.getUserData()
    this.setData({
      currentPageId: 1,
      currentSubPageId: 0,
      homePageTopBarSelected: -1,
      homePageTopBarTop: 0
    })
    await this.checkAdminPassword()
    await this.getCom(this.data.loginedUserInfo.type, false)
    this.refreshTitle()
    this.setData({
      showAppPage: 1
    })
    if (this.data.loginedUserInfo.type == 'admin') {
      await this.getChartData()
      this.prepareChartData()
    }
  },
  async getChartData() {
    let re22 = await tool.requestMethod("/statistics", {
      SF: this.data.tj_xc_sf,
      XQ: this.data.tj_xc_xq,
      LX: this.data.tj_xc_lx,
      DX: this.data.tj_xc_dx
    })
    this.setData({
      bgStatistics: re22.results
    })
  },
  getTitle() {
    if (this.data.currentPageId >= 2) return '巡查e速办'
    if (this.data.loginedUserInfo == undefined || this.data.loginedUserInfo == '') {
      return ''
    }
    if (this.data.currentSubPageId == 0) {
      return '主页'
    }
    if (this.data.currentSubPageId == 2) {
      return '管理'
    }
    return '功能'
  },
  async onShow() {

    if (this.data.loginedUserInfo == '' || this.data.canRefreshHomeData == false) return

    await this.checkLoginShowRegButton()
    if ((await this.checkAdminPassword()) == false) {
      this.setData({
        currentPageId: 1
      })
    }
    if (wx.getStorageSync('reLogin') == 'true') {
      wx.removeStorageSync('reLogin')
      wx.removeStorageSync('loginedUserInfo')
      this.setData({
        loginedUserInfo: '',
        currentPageId: 0,
        loginAccount: '',
        loginPassword: ''
      })
      this.setData({
        title: this.getTitle(),
      })
    }
    if (wx.getStorageSync('refreshComList') == 'true') {
      wx.removeStorageSync('refreshComList')
      this.getCom()
    }
    await this.getUserData()
  }
})